//
//  WeatherViewController.m
//  BuffetNews
//
//  Created by 李荃荃 on 14-10-27.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "WeatherViewController.h"
#import "AIMTableViewIndexBar.h"
#import "citySort.h"
#import "NetHandler.h"
#import "SearchBarViewController.h"
#import "NightModel.h"
#import "WebColor.h"
#import "Reachability.h"
#import <SystemConfiguration/SystemConfiguration.h>


@interface WeatherViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, AIMTableViewIndexBarDelegate, CLLocationManagerDelegate, MKMapViewDelegate>
@property (nonatomic, retain) UISearchBar *searchBar;
@property (nonatomic, retain) UITableView *plainTableView;     //  显示城市名的tableView
@property (nonatomic, retain) AIMTableViewIndexBar *indexBar;  //  旁边索引栏
@property (nonatomic, retain) NSArray *sections;               //  section数组
@property (nonatomic, retain) NSArray *rows;                   //  section中每个首字母对应的城市数组
@property (nonatomic, retain) NSMutableArray *hotCities;       //  热门城市数组
@property (nonatomic, retain) NSMutableArray *citiesName;      //  城市名数组

//  定位
@property(nonatomic , retain)CLLocationManager *LocationManager;
@property(nonatomic , assign)CLLocationCoordinate2D mylocation;

@property (nonatomic, retain) UIButton *buttonGPS;
@property (nonatomic, retain) NSDictionary *mapDic;    //  用来存储定位后获得的信息（国家，城市，市区，街道等）；

@end

@implementation WeatherViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.citiesName = [NSMutableArray array];
        self.mapDic = [NSDictionary dictionary];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"< 订阅" style:UIBarButtonItemStylePlain target:self action:@selector(barAction:)];
    
    self.title = @"选择所在城市";
    [self loadingView];
    [self loadingData];
    
}

- (void)loadingView
{
    //  搜索栏
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    self.searchBar.placeholder = @"输入城市名称";
    self.searchBar.delegate = self;
    self.searchBar.barStyle = UIBarStyleDefault;
    self.searchBar.showsBookmarkButton = NO;
    self.searchBar.showsCancelButton = NO;
    self.searchBar.showsSearchResultsButton = YES;
    self.searchBar.autocorrectionType = UITextAutocorrectionTypeDefault;
    self.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
    [self.view addSubview:_searchBar];
    [_searchBar release];
    
    //  定位按钮
    self.buttonGPS = [UIButton buttonWithType:UIButtonTypeSystem];
    self.buttonGPS.frame = CGRectMake(0, 40, self.view.frame.size.width, 40);
    
    //  判断夜间模式
    if ([NightModel shareInstance].open == 1) {
        self.buttonGPS.backgroundColor = [WebColor dimGray];
    } else {
        self.buttonGPS.backgroundColor = [UIColor whiteColor];
    }
    
    [self.buttonGPS setTitle:@"GPS定位" forState:UIControlStateNormal];
    [self.buttonGPS addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.buttonGPS];
    
    
    //  索引tableView
    self.indexBar = [[AIMTableViewIndexBar alloc] init];
    _indexBar.frame = CGRectMake(self.view.frame.size.width - 30, 70, 30, self.view.frame.size.height - 200);
    _indexBar.backgroundColor = [UIColor clearColor];
    
    //  城市tableView
    self.plainTableView = [[UITableView alloc] init];
    _plainTableView.frame =  CGRectMake(0, 70, self.view.frame.size.width, self.view.frame.size.height - 180);
    _plainTableView.delegate = self;
    _plainTableView.dataSource = self;
    
    [self.view addSubview:_plainTableView];
    [self.view addSubview:_indexBar];
    
    [_indexBar release];
    [_plainTableView release];
    
    }

- (void)loadingData
{
    
    citySort * ci = [[citySort alloc] init];
    
    //  所有城市
    NSMutableArray * arrA = [NSMutableArray array];
    arrA = [ci setSrot:@"a"];
    
    NSMutableArray * arrB = [NSMutableArray array];
    arrB = [ci setSrot:@"b"];
    
    NSMutableArray * arrC = [NSMutableArray array];
    arrC = [ci setSrot:@"c"];
    
    NSMutableArray * arrD = [NSMutableArray array];
    arrD = [ci setSrot:@"d"];
    
    NSMutableArray * arrE = [NSMutableArray array];
    arrE = [ci setSrot:@"e"];
    
    NSMutableArray * arrF = [NSMutableArray array];
    arrF = [ci setSrot:@"f"];
    
    NSMutableArray * arrG = [NSMutableArray array];
    arrG = [ci setSrot:@"g"];
    
    NSMutableArray * arrH = [NSMutableArray array];
    arrH = [ci setSrot:@"h"];
    
    NSMutableArray * arrJ = [NSMutableArray array];
    arrJ = [ci setSrot:@"j"];
    
    NSMutableArray * arrK = [NSMutableArray array];
    arrK = [ci setSrot:@"k"];
    
    NSMutableArray * arrL = [NSMutableArray array];
    arrL = [ci setSrot:@"l"];
    
    NSMutableArray * arrM = [NSMutableArray array];
    arrM = [ci setSrot:@"m"];
    
    NSMutableArray * arrN = [NSMutableArray array];
    arrN = [ci setSrot:@"n"];
    
    
    
    NSMutableArray * arrP = [NSMutableArray array];
    arrP = [ci setSrot:@"p"];
    
    NSMutableArray * arrQ = [NSMutableArray array];
    arrQ = [ci setSrot:@"q"];
    
    NSMutableArray * arrR = [NSMutableArray array];
    arrR = [ci setSrot:@"r"];
    
    NSMutableArray * arrS = [NSMutableArray array];
    arrS = [ci setSrot:@"s"];
    
    NSMutableArray * arrT = [NSMutableArray array];
    arrT = [ci setSrot:@"t"];
    
    NSMutableArray * arrW = [NSMutableArray array];
    arrW = [ci setSrot:@"w"];
    
    NSMutableArray * arrX = [NSMutableArray array];
    arrX = [ci setSrot:@"x"];
    
    NSMutableArray * arrY = [NSMutableArray array];
    arrY = [ci setSrot:@"y"];
    
    NSMutableArray * arrZ = [NSMutableArray array];
    arrZ = [ci setSrot:@"z"];
    
    
    //  热门城市
    self.hotCities = [ci hotCities];

    NSMutableArray *hotArr = [NSMutableArray array];
    for (NSDictionary *dic in self.hotCities) {
        NSString *string = [dic objectForKey:@"name"];
        [hotArr addObject:string];
    }

    
    self.sections = @[@"Hot Cities", @"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"J", @"K", @"L", @"M", @"N", @"P", @"Q", @"R", @"S", @"T", @"W", @"X", @"Y", @"Z"];
    
    self.rows = @[hotArr, arrA, arrB, arrC, arrD, arrE, arrF, arrG, arrH, arrJ, arrK, arrL, arrM, arrN,  arrP, arrQ, arrR, arrS, arrT, arrW, arrX, arrY, arrZ];
    
    
    for (NSArray *arr in self.rows) {
        for (NSString *str in arr) {
            [self.citiesName addObject:str];
        }
    }
    _indexBar.delegate = self;
    [ci release];
}

#pragma mark - tableview 协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    [_indexBar setIndexes:_sections];
    return [_sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_rows[section] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return _sections[section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];
    if (cell == nil){
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"pool"] autorelease];
    }
    cell.textLabel.text = [self.rows[indexPath.section] objectAtIndex:indexPath.row];
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if ([NightModel shareInstance].open == 1) {
        cell.backgroundColor = [WebColor dimGray];
        self.plainTableView.backgroundColor = [WebColor dimGray];
    } else {
        self.plainTableView.backgroundColor = [UIColor whiteColor];
    }
    
    return cell;
}

// 城市选择
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    BOOL reachable = [[Reachability reachabilityForInternetConnection] isReachable];
    
    if (!reachable) {
        UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"请检查您的网络连接状态" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] autorelease];
        [alertView show];
        
        
        
    } else {
    
    
    NSString *string = @"http://iphone.myzaker.com/zaker/get_weather.php?city=";//  城市接口，参数是城市名

        NSString *str = self.rows[indexPath.section][indexPath.row];            //  获得当前选择的城市的名字
    
        NSString *netStr = [string stringByAppendingString:str];

    
        [NetHandler networkWithURL:netStr comaletion:^(id result) {
            
            //  数据解析，给Model类赋值
            NSDictionary *dic = [NSDictionary dictionary];
            dic = [[result objectForKey:@"data"] objectForKey:@"datas"];
            self.city = [[CityWeather alloc] init];
            self.city.city = [dic objectForKey:@"city"];
            self.city.treal = [dic objectForKey:@"treal"];
            self.city.weather_day = [dic objectForKey:@"weather_day"];
            self.city.weather_night = [dic objectForKey:@"weather-night"];
            self.city.tmax = [dic objectForKey:@"tmax"];
            self.city.tmin = [dic objectForKey:@"tmin"];
            

        }];
    }
}
-(BOOL)isReachableViaWWAN
{
    return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}



#pragma mark - AIMTableViewIndexBar  协议方法
- (void)tableViewIndexBar:(AIMTableViewIndexBar *)indexBar didSelectSectionAtIndex:(NSInteger)index
{
    if ([_plainTableView numberOfSections] > index && index > -1) {
        [_plainTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index]
                              atScrollPosition:UITableViewScrollPositionTop
                                      animated:YES];
    }
}


//  返回首页 实现block
- (void)barAction:(UIBarButtonItem *)bar
{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center postNotificationName:@"weather" object:self.city];

    [self.navigationController popToRootViewControllerAnimated:YES];
}
//  搜索栏
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    SearchBarViewController *searchVC = [[SearchBarViewController alloc] init];
    
    searchVC.searchArray = self.citiesName; //  属性传值，将所有的城市名传到搜索页面中，用于城市名的搜索
    
    [self.navigationController pushViewController:searchVC animated:NO];
    [searchVC release];
}


#pragma mark - 城市定位

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *currentLocation = [locations lastObject];
    self.mylocation = currentLocation.coordinate;
    
//    NSLog(@"%f",self.mylocation.latitude);
//    NSLog(@"%f",self.mylocation.longitude);
    
    
    self.geocoder = [[CLGeocoder alloc]init];
    [self.geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        //        if (error == nil && [placemarks count] > 0) {
//        NSLog(@"currentLocation  %@",currentLocation);
        for (CLPlacemark *placeMark in placemarks) {
            self.mapDic = [placeMark addressDictionary];
            //  Country(国家)  State(城市)  SubLocality(区)

//            NSLog(@"  Country %@",[self.mapDic objectForKey:@"Country"]);
//            NSLog(@"State  %@", [self.mapDic objectForKey:@"State"]);
//            NSLog(@"City  %@", [self.mapDic objectForKey:@"City"]);
//            NSLog(@"Street %@", [self.mapDic objectForKey:@"Street"]);
            
            //            NSLog(@"%@", test);

            NSLog(@"  Country %@",[self.mapDic objectForKey:@"Country"]);
            NSLog(@"State  %@", [self.mapDic objectForKey:@"State"]);
            NSLog(@"City  %@", [self.mapDic objectForKey:@"City"]);
            NSLog(@"Street %@", [self.mapDic objectForKey:@"Street"]);


            
            
            [self.buttonGPS setTitle:[self.mapDic objectForKey:@"City"] forState:UIControlStateNormal];
            
            
            NSString *stringHttp = @"http://iphone.myzaker.com/zaker/get_weather.php?city=";
            NSString *string = [self.mapDic objectForKey:@"City"];
            int long length = [string length];
            NSString *string1 = [string substringToIndex:length - 1];
            NSString *cityName = [stringHttp stringByAppendingString:string1];

            
            [NetHandler networkWithURL:cityName comaletion:^(id result) {
                NSDictionary *dic = [NSDictionary dictionary];
                dic = [[result objectForKey:@"data"] objectForKey:@"datas"];
                self.city = [[CityWeather alloc] init];
                self.city.city = [dic objectForKey:@"city"];
                self.city.treal = [dic objectForKey:@"treal"];
                self.city.weather_day = [dic objectForKey:@"weather_day"];
                self.city.weather_night = [dic objectForKey:@"weather-night"];
                self.city.tmax = [dic objectForKey:@"tmax"];
                self.city.tmin = [dic objectForKey:@"tmin"];
//                NSLog(@"weather   :  %@", self.city.weather_day);
                
                
                //  消息中心， 参数是选中的城市名
                NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
                [center postNotificationName:@"weather" object:self.city];
            }];
        }
    }];
    [_geocoder release];
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
//    NSLog(@"失败了");
    [self.buttonGPS setTitle:@"定位失败" forState:UIControlStateNormal];
}

//  点击按钮时开始定位
-(void)buttonClicked:(UIButton *)button
{
    if ([CLLocationManager locationServicesEnabled]) {
        self.LocationManager = [[CLLocationManager alloc]init];
        self.LocationManager.delegate = self;
        
        //选择定位的方式为最优的状态.
        self.LocationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        //触发事件的最小距离
        self.LocationManager.distanceFilter = 1.0f;
        
        [self.LocationManager startUpdatingLocation];
  
    }
}

- (void)dealloc
{
    [_citiesName release];
    [_searchBar release];
    [_plainTableView release];
    [_sections release];
    [_rows release];
    [_indexBar release];
    [_hotCities release];
    [_geocoder release];
    [_LocationManager release];
    [super dealloc];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
//    NSLog(@"注意内存管理");
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
